from django.core.management.base import BaseCommand
from events.service.purchase_threading import PurchaseThread
import signal
import sys
from datetime import datetime
from django.utils.timezone import make_aware

class Command(BaseCommand):
    help = '启动购物模拟器'
    
    def add_arguments(self, parser):
        parser.add_argument('--start-datetime', type=str, help='开始时间 (YYYY-MM-DD HH:MM:SS)', required=False)
        parser.add_argument('--end-datetime', type=str, help='结束时间 (YYYY-MM-DD HH:MM:SS)', required=False)
    
    def __init__(self):
        super().__init__()
        self.simulator = None
        
    def handle_shutdown(self, signum, frame):
        self.stdout.write(self.style.WARNING('\n正在停止模拟器...'))
        if self.simulator:
            self.simulator.stop()
        sys.exit(0)

    def handle(self, *args, **options):
        # 解析时间参数
        start_datetime = None
        end_datetime = None
        
        if options['start_datetime'] and options['end_datetime']:
            try:
                start_datetime = make_aware(datetime.strptime(options['start_datetime'], '%Y-%m-%d %H:%M:%S'))
                end_datetime = make_aware(datetime.strptime(options['end_datetime'], '%Y-%m-%d %H:%M:%S'))
            except ValueError:
                self.stdout.write(self.style.ERROR('时间格式错误，请使用格式：YYYY-MM-DD HH:MM:SS'))
                return
            
        # 设置信号处理
        signal.signal(signal.SIGINT, self.handle_shutdown)
        signal.signal(signal.SIGTERM, self.handle_shutdown)
        
        # 创建模拟器实例
        self.simulator = PurchaseThread(max_threads=8, start_datetime=start_datetime, end_datetime=end_datetime)
        
        # 根据模式输出不同的启动信息
        if start_datetime and end_datetime:
            self.stdout.write(self.style.SUCCESS(f'正在启动购物模拟器（补数据模式）...\n模拟期间：{start_datetime} 至 {end_datetime}'))
        else:
            self.stdout.write(self.style.SUCCESS('正在启动购物模拟器（实时模式）...'))
            
        self.simulator.start()
        
        try:
            # 等待模拟完成
            self.simulator.simulation_thread.join()
            self.stdout.write(self.style.SUCCESS('模拟完成！'))
        except KeyboardInterrupt:
            self.handle_shutdown(None, None)